package com.shiro.controller;

import com.shiro.mapper.UserMapper;
import com.shiro.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author ZhangJunqi
 * @Date 2022/3/7 -22:38
 */
@Controller
public class MyController {
    @Autowired
    private UserMapper userMapper;

    @GetMapping({"/","/index"})
    public String helloIndex(Model model){
        model.addAttribute ("msg","hello shiro");
        Subject subject=SecurityUtils.getSubject ();
        User user = (User) subject.getPrincipal ();
        if (user!=null){
            model.addAttribute ("userName","当前用户："+user.getUserName ());
        }
        return "index";
    }

    @GetMapping("/user/add")
    public String addUser(){
        return "user/add";
    }

    @GetMapping("/user/update")
    public String updateUser(){
        return "user/update";
    }

    @GetMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @GetMapping("/login")
    public String login(String userName,String password,Model model){
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken (userName,password);
        //记住我
        //token.setRememberMe(true);
        try {
            currentUser.login(token);
            //currentUser.logout ();
            Session session=currentUser.getSession ();
            User user=(User)currentUser.getPrincipal ();
            session.setAttribute ("loginUser",user);
            return "redirect:index";
        } catch (UnknownAccountException e) {
            model.addAttribute ("msg","用户名错误");
            return "login";
        } catch (IncorrectCredentialsException ice) {
            model.addAttribute ("msg","密码错误");
            return "login";
        } catch (LockedAccountException lae) {
            model.addAttribute ("msg","用户锁定");
            return "login";
        }
    }

    //未授权页面
    @GetMapping("/unauthorized")
    @ResponseBody
    public String unauthorized(){
        return "<h1>未经授权的页面401</h1>";
    }

    @GetMapping("/loginOut")
    public String loginOut(Model model){
        Subject subject=SecurityUtils.getSubject ();
        subject.logout ();
        model.addAttribute ("msg","退出登录成功");
        return "login";
    }
}
